package com.smart.car.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smart.car.auth.utils.CookieUtils;
import com.smart.car.common.res.bean.ResponseResult;
import com.smart.car.common.res.exception.BusinessException;
import com.smart.car.gateway.config.JwtProperties;
import com.smart.car.gateway.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 网关的接口认证过滤器（token认证）
 *
 * @author zoutao
 * @date 2021/4/30
 */
@Slf4j
@Component
@EnableConfigurationProperties(JwtProperties.class)
public class AuthGatewayFilter implements GatewayFilter, Ordered {

    //spring的路径匹配器
    private final static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private JwtProperties jwtProperties;

    //排序规则，越小优先级越高
    @Override
    public int getOrder() {
        return -100;
    }

    /**
     * 网关JWT前置拦截器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /** 1.获取request请求和response响应 */
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //response.getHeaders().add("Content-Type","application/json; charset=utf-8");

        String url = exchange.getRequest().getURI().getPath();
        /** 2.跳过不需要验证的url */
        for (String skip : jwtProperties.getSkipAuthUrls()) {
            if (antPathMatcher.match(skip, url)) {
                //log.info("放行不需要验证的路径:{}",url);
                return chain.filter(exchange);
            }
        }
        /** 3.获取请求中的所有cookie */
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();

        /** TODO 4.判断cookies为空或不包含指定字段的token，这里会出现cookie跨域丢失的问题. */
        if (CollectionUtils.isEmpty(cookies) || !cookies.containsKey(this.jwtProperties.getCookieName())) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.error("401,您未登录或无访问权限！");
            return errorInfo(exchange, 401,"认证不通过，无访问权限！");
        }
        /** 5.如果请求头中有令牌则提取对应的cookie（token）出来解析 */
        HttpCookie cookie = cookies.getFirst(this.jwtProperties.getCookieName());
        log.info("获取到的token信息：{}",cookie);
        /** 6.校验cookie */
        try {
            log.info("校验cookie（token）开始！");
            //从token中解析用户信息并设置到Header中去
            Map<String, Object> token = JwtUtils.getInfoFromToken(cookie.getValue(), this.jwtProperties.getPublicKey());
            log.info("token认证通过，放行："+token);
        } catch (Exception e) {
            e.printStackTrace();
            /** 7. 解析jwt令牌出错, 说明令牌过期或伪造等不合法 */
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        /** 8.认证通过放行 */
        return chain.filter(exchange);
    }


    /**
     * 自定义过滤器中直接返回错误结果
     * 返回response
     * @param exchange
     * @param message  异常信息
     * @param status   data中的status
     * @return
     */
    public static Mono<Void> errorInfo(ServerWebExchange exchange,Integer code, String message ) {
        // 自定义返回格式
        Map<String, Object> resultMap = new HashMap<>(8);
        resultMap.put("code", code == null ? 500 : code);
        resultMap.put("msg", StringUtils.isBlank(message) ? "认证不通过，无权访问！" : message);
        resultMap.put("data", null);
        return Mono.defer(() -> {
            byte[] bytes;
            try {
                bytes = new ObjectMapper().writeValueAsBytes(resultMap);
            } catch (JsonProcessingException e) {
                log.error("网关响应异常：", e);
                throw new BusinessException("信息序列化异常");
            } catch (Exception e) {
                log.error("网关响应异常：", e);
                throw new BusinessException("写入响应异常");
            }
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        });
    }

}
